import set from '@dfeidao/atom-web/global/set';
import { IFeidaoAiBrowserComponent } from '@dfeidao/atom-web/interfaces';
// import service from '@dfeidao/atom-web/msg/service';
import error from '@dfeidao/atom-web/msgbox/error';
import get_dom_by_id from '@dfeidao/atom-web/ui/get-dom-by-id';
import direct_to from '@dfeidao/atom-web/url/direct-to';
import { post } from '@dfeidao/send-msg/browser/request';
import { login, productid, spaceid } from './../../atom/config';
import a001 from './a001';

export default async function a002(fd: IFeidaoAiBrowserComponent) {
	// todo
	const usercode = get_dom_by_id(fd.data.node, 'usercode') as HTMLInputElement;
	if (!usercode.value) {
		error('账号密码不能为空');
		await a001(fd);
		return;
	}
	const user_pwd = get_dom_by_id(fd.data.node, 'user_pwd') as HTMLInputElement;
	if (!user_pwd.value) {
		error('账号密码不能为空');
		await a001(fd);
		return;
	}
	const captcha = get_dom_by_id(fd.data.node, 'captcha') as HTMLInputElement;
	if (!captcha.value) {
		error('验证码不能为空');
		await a001(fd);
		return;
	}
	try {
		const body = ({ usercode: usercode.value, password: user_pwd.value, captcha: captcha.value, spaceid, productid });
		// 调用custom-login接口
		const res1 = await post(login, JSON.stringify(body)) as { usercode: string, user_name: string, productid: string, sessionid: string };
		// const res = await service('busiservice.antcart.phonelogin', body) as { usercode: string };
		// set('sessionid', res1.sessionid);
		set('user_no', res1.usercode);
		const backurl = fd.data.params.backurl as string;
		if (backurl) {
			direct_to(backurl);
		} else {
			direct_to('home.html');
		}
	} catch (err) {
		// console.log(err);
		let msg = '';
		try {
			msg = JSON.parse(err.message).msg;
		} catch (error) {
			msg = err.message;
		}
		if (msg.search("手机号") !== -1) {
			msg = "账号或密码错误";
		}
		if (msg.search("密码") !== -1) {
			msg = "账号或密码错误";
		}
		error(msg);
		await a001(fd);
		// throw Error(msg);
	}
}

